package cn.elead.chaos.sso.server.web.system.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.elead.chaos.core.converter.Convert;
import cn.elead.chaos.core.util.StringUtils;
import cn.elead.chaos.framework.web.global.ApiAssert;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import cn.elead.chaos.sso.server.constants.UserConstants;
import cn.elead.chaos.sso.server.utli.Current;
import cn.elead.chaos.sso.server.web.system.domain.SysPost;
import cn.elead.chaos.sso.server.web.system.domain.SysRole;
import cn.elead.chaos.sso.server.web.system.domain.SysUser;
import cn.elead.chaos.sso.server.web.system.domain.SysUserPost;
import cn.elead.chaos.sso.server.web.system.domain.SysUserRole;
import cn.elead.chaos.sso.server.web.system.mapper.SysPostMapper;
import cn.elead.chaos.sso.server.web.system.mapper.SysRoleMapper;
import cn.elead.chaos.sso.server.web.system.mapper.SysUserMapper;
import cn.elead.chaos.sso.server.web.system.mapper.SysUserPostMapper;
import cn.elead.chaos.sso.server.web.system.mapper.SysUserRoleMapper;
import cn.elead.chaos.sso.server.web.system.service.ISysConfigService;
import cn.elead.chaos.sso.server.web.system.service.ISysUserService;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Slf4j
@Service
public class SysUserServiceImpl implements ISysUserService {

	@Autowired
	private SysUserMapper userMapper;

	@Autowired
	private SysRoleMapper roleMapper;

	@Autowired
	private SysPostMapper postMapper;

	@Autowired
	private SysUserPostMapper userPostMapper;

	@Autowired
	private SysUserRoleMapper userRoleMapper;

	@Autowired
	private ISysConfigService configService;

	@Autowired
	private SysPasswordService sysPasswordService;

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 根据条件分页查询用户列表
	 * 
	 * @param user 用户信息
	 * @return 用户信息集合信息
	 */
	@Override
	// @DataScope(deptAlias = "d", userAlias = "u")
	public List<SysUser> selectUserList(SysUser user) {
		return userMapper.selectUserList(user);
	}

	/**
	 * 根据条件分页查询已分配用户角色列表
	 * 
	 * @param user 用户信息
	 * @return 用户信息集合信息
	 */
	// @DataScope(deptAlias = "d", userAlias = "u")
	public List<SysUser> selectAllocatedList(SysUser user) {
		return userMapper.selectAllocatedList(user);
	}

	/**
	 * 根据条件分页查询未分配用户角色列表
	 * 
	 * @param user 用户信息
	 * @return 用户信息集合信息
	 */
	// @DataScope(deptAlias = "d", userAlias = "u")
	public List<SysUser> selectUnallocatedList(SysUser user) {
		return userMapper.selectUnallocatedList(user);
	}

	/**
	 * 通过用户名查询用户
	 * 
	 * @param userName 用户名
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserByLoginName(String userName) {
		return userMapper.selectUserByLoginName(userName);
	}

	/**
	 * 通过手机号码查询用户
	 * 
	 * @param phoneNumber 手机号码
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserByPhoneNumber(String phoneNumber) {
		return userMapper.selectUserByPhoneNumber(phoneNumber);
	}

	/**
	 * 通过邮箱查询用户
	 * 
	 * @param email 邮箱
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserByEmail(String email) {
		return userMapper.selectUserByEmail(email);
	}

	/**
	 * 通过用户ID查询用户
	 * 
	 * @param userId 用户ID
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserById(String userId) {
		return userMapper.selectUserById(userId);
	}
	
    /**
     * 通过用户IDs查询用户
     * 
     * @param userIds 用户ID
     * @return 用户对象信息
     */
    public List<SysUser> selectUserByIds(List<String> userIds){
    	return userMapper.selectUserByIds(userIds);
    }


	/**
	 * 通过用户ID删除用户
	 * 
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	public int deleteUserById(String userId) {
		// 删除用户与角色关联
		userRoleMapper.deleteUserRoleByUserId(userId);
		// 删除用户与岗位表
		userPostMapper.deleteUserPostByUserId(userId);
		return userMapper.deleteUserById(userId);
	}

	/**
	 * 批量删除用户信息
	 * 
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteUserByIds(String ids) {
		String[] userIds = Convert.toStrArray(ids);
		for (String userId : userIds) {
			checkUserAllowed(new SysUser(userId));
		}
		return userMapper.deleteUserByIds(userIds);
	}

	/**
	 * 新增保存用户信息
	 * 
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	@Transactional
	public int insertUser(SysUser user) {
		// 新增用户信息
		int rows = userMapper.insertUser(user);
		// 新增用户岗位关联
		insertUserPost(user);
		// 新增用户与角色管理
		insertUserRole(user);
		return rows;
	}

	/**
	 * 修改保存用户信息
	 * 
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	@Transactional
	public int updateUser(SysUser user) {
		String userId = user.getUserId();
		// 删除用户与角色关联
		userRoleMapper.deleteUserRoleByUserId(userId);
		// 新增用户与角色管理
		insertUserRole(user);
		// 删除用户与岗位关联
		userPostMapper.deleteUserPostByUserId(userId);
		// 新增用户与岗位管理
		insertUserPost(user);
		return userMapper.updateUser(user);
	}

	/**
	 * 修改用户个人详细信息
	 * 
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int updateUserInfo(SysUser user) {
		return userMapper.updateUser(user);
	}

	/**
	 * 修改用户密码
	 * 
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int resetUserPwd(SysUser user) {
		return updateUserInfo(user);
	}

	/**
	 * 新增用户角色信息
	 * 
	 * @param user 用户对象
	 */
	public void insertUserRole(SysUser user) {
		Long[] roles = user.getRoleIds();
		if (ObjectUtil.isNotNull(roles)) {
			// 新增用户与角色管理
			List<SysUserRole> list = new ArrayList<SysUserRole>();
			for (Long roleId : roles) {
				SysUserRole ur = new SysUserRole();
				ur.setUserId(user.getUserId());
				ur.setRoleId(roleId);
				list.add(ur);
			}
			if (list.size() > 0) {
				userRoleMapper.batchUserRole(list);
			}
		}
	}

	/**
	 * 新增用户岗位信息
	 * 
	 * @param user 用户对象
	 */
	public void insertUserPost(SysUser user) {
		Long[] posts = user.getPostIds();
		if (ObjectUtil.isNotNull(posts)) {
			// 新增用户与岗位管理
			List<SysUserPost> list = new ArrayList<SysUserPost>();
			for (Long postId : posts) {
				SysUserPost up = new SysUserPost();
				up.setUserId(user.getUserId());
				up.setPostId(postId);
				list.add(up);
			}
			if (list.size() > 0) {
				userPostMapper.batchUserPost(list);
			}
		}
	}

	/**
	 * 校验登录名称是否唯一
	 * 
	 * @param loginName 用户名
	 * @return
	 */
	@Override
	public int checkLoginNameUnique(String loginName) {
		int count = userMapper.checkLoginNameUnique(loginName);
		if (count > 0) {
			return UserConstants.USER_NAME_NOT_UNIQUE;
		}
		return UserConstants.USER_NAME_UNIQUE;
	}

	/**
	 * 校验用户名称是否唯一
	 *
	 * @param user 用户信息
	 * @return
	 */
	@Override
	public int checkPhoneUnique(SysUser user) {
		String userId = ObjectUtil.isNull(user.getUserId()) ? "-1" : user.getUserId();
		SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
		if (ObjectUtil.isNotNull(info) && !StringUtils.equals(info.getUserId(), userId)) {
			return UserConstants.USER_PHONE_NOT_UNIQUE;
		}
		return UserConstants.USER_PHONE_UNIQUE;
	}

	/**
	 * 校验email是否唯一
	 *
	 * @param user 用户信息
	 * @return
	 */
	@Override
	public int checkEmailUnique(SysUser user) {
		String userId = ObjectUtil.isNull(user.getUserId()) ? "-1" : user.getUserId();
		SysUser info = userMapper.checkEmailUnique(user.getEmail());
		if (ObjectUtil.isNotNull(info) && !StringUtils.equals(info.getUserId(), userId)) {
			return UserConstants.USER_EMAIL_NOT_UNIQUE;
		}
		return UserConstants.USER_EMAIL_UNIQUE;
	}

	/**
	 * 校验用户是否允许操作
	 * 
	 * @param user 用户信息
	 */
	public void checkUserAllowed(SysUser user) {
		if (ObjectUtil.isNotNull(user.getUserId()) && Current.isAdmin(user)) {
			ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("不允许操作超级管理员用户"));
		}
	}

	/**
	 * 查询用户所属角色组
	 * 
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	public String selectUserRoleGroup(String userId) {
		List<SysRole> list = roleMapper.selectRolesByUserId(userId);
		StringBuffer idsStr = new StringBuffer();
		for (SysRole role : list) {
			idsStr.append(role.getRoleName()).append(",");
		}
		if (StringUtils.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}

	/**
	 * 查询用户所属岗位组
	 * 
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	public String selectUserPostGroup(String userId) {
		List<SysPost> list = postMapper.selectPostsByUserId(userId);
		StringBuffer idsStr = new StringBuffer();
		for (SysPost post : list) {
			idsStr.append(post.getPostName()).append(",");
		}
		if (StringUtils.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}

	/**
	 * 导入用户数据
	 * 
	 * @param userList        用户数据列表
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @param operName        操作用户
	 * @return 结果
	 */
	@Override
	public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
		if (ObjectUtil.isNull(userList) || userList.size() == 0) {
			ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("导入用户数据不能为空！"));
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		// String password = configService.selectConfigByKey("sys.user.initPassword");
		for (SysUser user : userList) {
			try {
				// 验证是否存在这个用户
				SysUser u = userMapper.selectUserByLoginName(user.getLoginName());
				if (ObjectUtil.isNull(u)) {
					// user.setPassword(Md5Utils.hash(user.getLoginName() + password));
					user.setCreateBy(operName);
					this.insertUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
				} else if (isUpdateSupport) {
					user.setUpdateBy(operName);
					this.updateUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
				}
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert(failureMsg.toString()));
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

	/**
	 * 用户状态修改
	 * 
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int changeStatus(SysUser user) {
		return userMapper.updateUser(user);
	}

	/**
	 * 定时同步用户
	 */
	@Override
	@Transactional
	public void syncUser() {

		HttpHeaders headers = new HttpHeaders();// header参数
		headers.add("username", "sso");
		headers.add("password", "sso");
		headers.setContentType(MediaType.APPLICATION_JSON);

		HttpEntity<Void> request = new HttpEntity<>(headers); // 组装

		String url = "http://oa.e-lead.cn:8090/timesheet/outer/usersSSO";

		ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, request, JSONObject.class);

		if (response.getStatusCode() == HttpStatus.OK) {

			JSONObject body = response.getBody();

			JSONArray datas = body.getJSONArray("data");

			Iterator<Object> iterator = datas.iterator();

			while (iterator.hasNext()) {
				JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(iterator.next()));
				SysUser user = new SysUser();
				String id = data.getString("work_no");
				if (StringUtils.isBlank(id)) {
					System.err.println(data);
				}
				user.setUserId(data.getString("work_no"));
				user.setUserName(data.getString("name"));
				// user.setPinYin(ChineseToSpell.getPingYin(data.getString("name")));
				user.setCardId(data.getString("id_card"));
				user.setStatus(data.getString("state"));
				user.setLoginName(data.getString("account"));
				user.setUserType(1);
				// user.setEntryDate(data.getDate("entry_date"));
				// user.setLeaveDate(data.getDate("leave_date"));
				// user.setDepartment(data.getString("department"));
				user.setCreateTime(new Date());
				user.setUpdateTime(new Date());
				SysUser entity = userMapper.selectUserById(user.getUserId());
				if (ObjectUtil.isNotEmpty(entity)) {
					if (user.getStatus().equals(entity.getStatus())) {
						continue;
					}
					// user.setPasswordStatus(entity.getPasswordStatus());
					userMapper.updateUser(user);
				} else {
					userMapper.insertUser(user);
				}
			}
		}
	}

	/**
	 * 初始密码
	 */
	@Override
	public void initPassword() {

		SysUser user = new SysUser();

		Map<String, Object> params = new HashMap<String, Object>();
		String beginCreateTime = LocalDate.now().minusDays(3).format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
		String endCreateTime = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
		params.put("beginCreateTime", beginCreateTime);
		params.put("endCreateTime", endCreateTime);

		user.setParams(params);
		List<SysUser> users = userMapper.selectUserList(user);
		for (SysUser sysUser : users) {
			String cardId = sysUser.getCardId();
			String last = StringUtils.sub(cardId, 12, 18);
			if (StringUtils.isBlank(last)) {
				last = configService.selectConfigByKey("sys.user.initPassword");
			}
			user.setPassword(sysPasswordService.encryptPassword(last));
			user.setSalt(last);
			user.setUserId(sysUser.getUserId());
			userMapper.updateUser(user);
		}

	}

}
